//
//  TitleNavigationTableView.m
//  mcrmSAAS
//
//  Created by wjxfhxy on 15/7/10.
//  Copyright (c) 2015年 GuangZhouXuanWu. All rights reserved.
//

#import "TitleNavigationTableView.h"

#import "TitleNavigationBar.h"

@interface TitleNavigationTableView ()<UITableViewDataSource,UITableViewDelegate,XUITableViewDelegate,TitleNavigationBarDelegate>
{
    TitleNavigationBar *_bar;
    
    NSMutableArray *_tableViews;
}
@end

@implementation TitleNavigationTableView


-(id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    
    self.backgroundColor = [UIColor whiteColor];
    
    _tableViews = [NSMutableArray new];
    
    _bar = [[TitleNavigationBar alloc]initWithFrame:CGRectMake(0, 0, self.width, 36)];
    _bar.delegate = self;
    
    [self addSubview:_bar];
    
    return self;
}

-(void)layoutSubviews
{
    [super layoutSubviews];
    
//    _bar.width = self.width;
//    
//    for(NSUInteger i = 0; i < _tableViews.count ;i++)
//    {
//        UITableView *tableView = _tableViews[i];
//        tableView.frame = CGRectMake(_bar.width * i, _bar.bottom, _bar.width, self.height - _bar.height);
//    }
}

- (NSUInteger)allocTableViewTag
{
    return (_tableViews.count + 1) * 1000;
}

- (NSUInteger)tableViewTag:(UITableView*)tableView
{
    return (tableView.tag / 1000 ) -1;
}

//-(void)viewDidLayoutSubviews
//{
//    [super viewDidLayoutSubviews];
//    
//    if ([_ctable respondsToSelector:@selector(setSeparatorInset:)])
//    {
//        [_ctable setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];
//    }
//    
//    if ([_ctable respondsToSelector:@selector(setLayoutMargins:)])
//    {
//#ifdef __IPHONE_8_0
//        [_ctable setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)];
//#endif
//    }
//}

//-(void)setDelegate:(id<TitleNavigationTableViewDelegate>)delegate
//{
//    _delegate = delegate;
//}

-(void)addTableContent:(BOOL)animated
{
    CGFloat x = 0;
    x = _tableViews.count <=0 ? 0 : ((UIView*)_tableViews[_tableViews.count - 1]).right;
    XUITableView *tableView = [[XUITableView alloc]initWithFrame:CGRectMake(x, _bar.bottom, _bar.width, self.height - _bar.height) style:UITableViewStylePlain];
    if([_delegate respondsToSelector:@selector(refreshCurrentTableViewContentLastUpdateTime:)])
    {
        [tableView createRefreshHead];
        tableView.refreshHeaderView.endRefreshingImmediately = YES;
    }
    tableView.separatorExistFollowCell = YES;
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.tag = [self allocTableViewTag];
    if ([tableView respondsToSelector:@selector(setSeparatorInset:)])
        [tableView setSeparatorInset:UIEdgeInsetsZero];
#ifdef __IPHONE_8_0
    if ([tableView respondsToSelector:@selector(setLayoutMargins:)])
        [tableView setLayoutMargins:UIEdgeInsetsZero];
#endif
    [self addSubview:tableView];
    
    [_tableViews addObject:tableView];
    
    NSString *title = [_delegate titleNavigationTableView:self titleAtPageIndex:[self tableViewTag:tableView]];
    
    [_bar addTitle:title];
    
    if(animated == YES && _tableViews.count > 1)
    {
        [UIView animateWithDuration:0.3 animations:^
        {
            for(NSUInteger i = 0; i < _tableViews.count ;i++)
            {
                UITableView *tableView = _tableViews[i];
                tableView.left -= tableView.width;
            }
        } completion:^(BOOL finished)
        {
            ((UITableView*)_tableViews[_tableViews.count - 2]).hidden = YES;
        }];
    }
}

-(void)reloadCurrentTableContent
{
    [(UITableView*)[_tableViews lastObject] reloadData];
}

-(void)beginUpdates
{
    [(UITableView*)[_tableViews lastObject] beginUpdates];
}

-(void)endUpdates
{
    [(UITableView*)[_tableViews lastObject] endUpdates];
}

-(void)reloadCurrentTableContentAtRow:(NSUInteger)row animated:(BOOL)animated
{
    [(UITableView*)[_tableViews lastObject] reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:row inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
}

-(void)insertCurrentTabelContentAtRow:(NSUInteger)row animated:(BOOL)animated
{
    [(UITableView*)[_tableViews lastObject] insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:row inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
}

-(void)deleteCurrentTabelContentAtRow:(NSUInteger)row animated:(BOOL)animated
{
    [(UITableView*)[_tableViews lastObject] deleteRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:row inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
}

-(void)reloadTableContentAtPageIndex:(NSUInteger)index
{
    [(UITableView*)_tableViews[index] reloadData];
}

-(UITableViewCell*)currentTabelCellAtIndex:(NSUInteger)row
{
    return [(UITableView*)[_tableViews lastObject] cellForRowAtIndexPath:[NSIndexPath indexPathForRow:row inSection:0]];
}

-(UITableViewCell*)currentTabelCellWithTag:(NSString*)tag
{
    return [(XUITableView*)[_tableViews lastObject] findVisibleCellWithTag:tag];
}

-(void)scrollToRowAtIndex:(NSUInteger)index atScrollPosition:(UITableViewScrollPosition)scrollPosition animated:(BOOL)animate
{
    [(UITableView*)[_tableViews lastObject] scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0] atScrollPosition:scrollPosition animated:animate];
}

-(void)removeContentFromIndex:(NSUInteger)index animated:(BOOL)animated
{
    NSArray *ar = [_tableViews objectsAtIndexes:[[NSIndexSet alloc]initWithIndexesInRange:NSMakeRange(index + 1, _tableViews.count - (index + 1))]];
    
    {
        NSArray *ar = [_tableViews objectsAtIndexes:[[NSIndexSet alloc]initWithIndexesInRange:NSMakeRange(index, _tableViews.count - index)]];
        for(NSUInteger i = 0; i < ar.count ;i++)
        {
            UITableView *tableView = ar[i];
            tableView.hidden = NO;
        }
    }
    
    if(animated == YES )
    {
        if([_delegate respondsToSelector:@selector(titleNavigationTableView:willReappearPageIndex:)])
            [_delegate titleNavigationTableView:self willReappearPageIndex:index];
        
        [UIView animateWithDuration:0.3 animations:^
        {
            for(NSUInteger i = 0; i < _tableViews.count ;i++)
            {
                UITableView *tableView = _tableViews[i];
                tableView.left += tableView.width * ar.count;
            }
        } completion:^(BOOL finished)
        {
            [ar makeObjectsPerformSelector:@selector(removeFromSuperview)];
            [_tableViews removeObjectsInArray:ar];
            
            [_bar removeTitleFromIndex:index];
        }];
    }
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)])
    {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
#ifdef __IPHONE_8_0
    if ([cell respondsToSelector:@selector(setLayoutMargins:)])
    {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
#endif
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [_delegate titleNavigationTableView:self heightForRow:indexPath.row atPageIndex:[self tableViewTag:tableView]];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_delegate titleNavigationTableView:self numberOfRowAtPageIndex:[self tableViewTag:tableView]];
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    XUITableViewCell*(^reuseCell)(NSString *reuseIdentifier) = ^XUITableViewCell*(NSString *reuseIdentifier)
    {
        return (XUITableViewCell*)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    };
    
    XUITableViewCell *cell = [_delegate titleNavigationTableView:self reuseCell:reuseCell forRow:indexPath.row atPageIndex:[self tableViewTag:tableView]];
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if([_delegate respondsToSelector:@selector(titleNavigationTableView:didSelectedRow:atPageIndex:)])
        [_delegate titleNavigationTableView:self didSelectedRow:indexPath.row atPageIndex:[self tableViewTag:tableView]];
}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    if([_delegate respondsToSelector:@selector(titleNavigationTableViewWillBeginDragging:)])
        [_delegate titleNavigationTableViewWillBeginDragging:self];
}

-(void)tableView:(XUITableView *)tableview refreshTableContent:(void (^)())asyncEndRefreshing
{
    if([_delegate respondsToSelector:@selector(refreshCurrentTableViewContent:)])
        [_delegate refreshCurrentTableViewContent:self];
}

- (id)contentLastRefreshUpdateTimeOfTableView:(XUITableView *)tableview
{
    if([_delegate respondsToSelector:@selector(refreshCurrentTableViewContentLastUpdateTime:)])
        return [_delegate refreshCurrentTableViewContentLastUpdateTime:self];
    return nil;
}

-(void)titleNavigationBar:(TitleNavigationBar *)bar selectedAtIndex:(NSUInteger)index
{
    if([_delegate respondsToSelector:@selector(titleNavigationTableView:didSelectedTitleAtPageIndex:)])
        [_delegate titleNavigationTableView:self didSelectedTitleAtPageIndex:index];
}

@end
